﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using TireService.Data;
using System.Configuration;
using System.Collections.Specialized;
using System.Text;
using System.Collections;
using System.Web.Security;
using DevExpress.Web.ASPxEditors;
using System.IO;
using DevExpress.Web.ASPxCallback;

namespace TireService.Website
{
    public partial class Bestil : System.Web.UI.Page
    {
        #region Public Properties

        public int StepNumber
        {
            get
            {
                if (ViewState["_stepnumber"] != null)
                    return (int)ViewState["_stepnumber"];
                else
                    return 1;
            }
            set
            {
                ViewState["_stepnumber"] = value;
            }
        }

        public bool OrderingCompleted
        {
            get
            {
                if (ViewState["_orderingcompleted"] != null)
                    return (bool)ViewState["_orderingcompleted"];
                else
                    return false;
            }
            set
            {
                ViewState["_orderingcompleted"] = value;
            }
        }

        public bool PaymentDone
        {
            get
            {
                if (ViewState["_paymentdone"] != null)
                    return (bool)ViewState["_paymentdone"];
                else
                    return false;
            }
            set
            {
                ViewState["_paymentdone"] = value;
            }
        }

        public int PreSelectedSubscriptionId
        {
            get
            {
                if (ViewState["_preselectedsubscriptionid"] != null)
                    return (int)ViewState["_preselectedsubscriptionid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_preselectedsubscriptionid"] = value;
            }
        }

        public Guid CouponCode
        {
            get
            {
                if (ViewState["_couponcode"] != null)
                    return (Guid)ViewState["_couponcode"];
                else
                    return Guid.Empty;
            }
            set
            {
                ViewState["_couponcode"] = value;
            }
        }

        #endregion

        protected void Page_Init(object sender, EventArgs e)
        {
            // Register export button as full postback - otherwise it wount work because it is inside a update panel
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.btnPaypalPayment.FindControl("btnPaypalPayment"));
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Action"] == "Reset")
            {
                ResetSignupForm();
            }

            if (Page.IsPostBack != true)
            {
                TireServiceDB db = new TireServiceDB();

                // Reset modal popup panels
                pNeedHelp.Visible = true;
                pEmailSend.Visible = false;

                // Bind subscription data to radiobutton list
                rblSubscription.DataSource = db.GetSubscription().Where(p => p.InActive == false & p.Business == false).OrderBy(p => p.OrderingSequence);
                rblSubscription.TextField = "Description";
                rblSubscription.ValueField = "SubscriptionId";
                rblSubscription.DataBind();

                // Get data for dropdownlist
                ddlCountry.DataSource = db.GetCountries();
                ddlCountry.ValueField = "CountryId";
                ddlCountry.TextField = "CountryName";
                ddlCountry.DataBind();

                // Get data for car brand dropdownlist
                ddlCarBrand.DataSource = db.GetCarBrand();
                ddlCarBrand.ValueField = "CarBrandId";
                ddlCarBrand.TextField = "Description";
                ddlCarBrand.DataBind();

                int TodayYear = DateTime.Now.Year;

                for (int i = TodayYear; i > 1969; i--)
                {
                    //DevExpress.Web.ASPxEditors.collect
                    ListEditItem item = new ListEditItem();
                    item.Value = i;
                    item.Text = i.ToString();
                    txtYear.Items.Add(item);
                }

                ChangeFormUI(this.StepNumber, this.PaymentDone);

                db.Dispose();

                if (Request.QueryString["Id"] != null)
                {
                    try 
	                {
                        rblSubscription.Value = Request.QueryString["Id"];

                        SubscriptionSelected(Convert.ToInt32(rblSubscription.Value));
	                }
	                catch (Exception)
	                {
		                // Nothing
	                }
                }

                // Add javascript that disables payment button when user clicks
                btnPaypalPayment.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnPaypalPayment).ToString());
                
                // Add javascript that disables approve button when user clicks
                btnApproveSignUp.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnApproveSignUp).ToString());
            }        
        }

        /// <summary>
        /// Function that resets signup form
        /// </summary>
        private void ResetSignupForm()
        {
            this.StepNumber = 1;
            this.PaymentDone = false;
            this.OrderingCompleted = false;
        }

        /// <summary>
        /// Function that handle change in signup form
        /// </summary>
        /// <param name="StepNumber">Number for the step to change to</param>
        /// <param name="PaymentDone">True/False value indicating if payment has been done</param>
        protected void ChangeFormUI(int StepNumber, bool PaymentDone)
        {
            // Show/hide cancel signup
            btnCancelSignup.Visible = (this.PaymentDone != true);

            // Show correct step UI
            hlStep1.Font.Bold = (StepNumber == 1);
            step1SubscriptionChoice.Visible = (StepNumber == 1);
            hlStep2.Font.Bold = (StepNumber == 2);
            step2CustomerInformation.Visible = (StepNumber == 2);
            hlStep3.Font.Bold = (StepNumber == 3);
            step3CarInformation.Visible = (StepNumber == 3);
            hlStep4.Font.Bold = (StepNumber == 4);
            step4Approval.Visible = (StepNumber == 4);
            hlStep5.Font.Bold = (StepNumber == 5);
            step5Payment.Visible = (StepNumber == 5);

            switch (StepNumber)
            {
                case 1:
                    btnPreviousStep.Visible = false;
                    btnNextStep.Visible = true;
                    btnNextStep.Text = "Videre ->";
                    btnNextStep.ValidationGroup = "Step1";
                    btnApproveSignUp.Visible = false;

                    break;
                case 2:
                    btnPreviousStep.Visible = false;
                    btnNextStep.Visible = true;
                    btnNextStep.Text = "Videre ->";
                    btnNextStep.ValidationGroup = "Step2";
                    btnApproveSignUp.Visible = false;

                    break;
                case 3:
                    btnPreviousStep.Visible = true;
                    btnPreviousStep.Text = "<- Tilbage";
                    btnNextStep.Visible = true;
                    btnNextStep.Text = "Videre ->";
                    btnNextStep.ValidationGroup = "Step3";
                    btnApproveSignUp.Visible = false;

                    // Set primary address checkbox
                    rbPrimaryAddressTimeInterval.Items.Clear();
                    DevExpress.Web.ASPxEditors.ListEditItem itemPrimary = new DevExpress.Web.ASPxEditors.ListEditItem();
                    itemPrimary.Value = "true";
                    itemPrimary.Text = txtAddress.Text + ", " + txtZipCode.Text + " " + txtCity.Text;
                    rbPrimaryAddressTimeInterval.Items.Add(itemPrimary);

                    if (txtSecondaryAddress.Text != "")
                    {
                        DevExpress.Web.ASPxEditors.ListEditItem itemSecondary = new DevExpress.Web.ASPxEditors.ListEditItem();
                        itemSecondary.Value = "false";
                        itemSecondary.Text = txtSecondaryAddress.Text + ", " + txtSecondaryZipCode.Text + " " + txtSecondaryCity.Text;
                        rbPrimaryAddressTimeInterval.Items.Add(itemSecondary);
                    }

                    break;
                case 4:
                    btnPreviousStep.Visible = true;
                    btnPreviousStep.Text = "<- Tilbage";
                    btnNextStep.Visible = false;
                    btnNextStep.Text = "Til betaling ->";
                    btnNextStep.ValidationGroup = "Step4";
                    btnApproveSignUp.Visible = true;
                    btnApproveSignUp.Text = "Godkend bestilling ->";
                    btnApproveSignUp.ValidationGroup = "Step4";

                    break;
                case 5:
                    btnCancelSignup.Visible = false; // Possible to cancel signup anymore
                    btnPreviousStep.Visible = false; // Not possible to go back anymore - ordering completed
                    btnNextStep.Visible = false;
                    btnApproveSignUp.Visible = false;
                    pSubscriptionText.Visible = (rblSubscription.SelectedItem.Value.ToString() != "4");
                    pNoneSubscriptionText.Visible = (rblSubscription.SelectedItem.Value.ToString() == "4");

                    break;
            }
        }

        /// <summary>
        /// Function that sends email to customer with order confirmation on signup
        /// </summary>
        /// <param name="CustomerEmail">Customer email that this email will be send to</param>
        /// <param name="CustomerName">Name on customer</param>
        /// <param name="SubscriptionNumber">Unik subscription number (CustomerId-SubscriptionId)</param>
        /// <param name="InvoiceId">Unik Guid number for invoice</param>
        /// <param name="SubscriptionId">Id on subscription</param>
        /// <param name="attachment">Byte array for invoice file</param>
        /// <param name="FileName">Name on file to attach email</param>
        private void SendEmail(string CustomerEmail, string CustomerName, string SubscriptionNumber, string InvoiceId, int SubscriptionId, byte[] attachment, string FileName)
        {
            string Subject = "Bestilling gennemført - Abonnement " + SubscriptionNumber;
            bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));

            EmailNotification.EmailNotification message = new EmailNotification.EmailNotification();
            
            Shared email = new Shared();

            if (SubscriptionId == 4)
            {
                // Change subject on email
                Subject = "Bestilling af enkelt hjulskift gennemført - bestillingsnr " + SubscriptionNumber;
            }

            MemoryStream attach = new MemoryStream();
            attach.Write(attachment, 0, attachment.Length);
            attach.Position = 0;

            // Send email to customer with us on bcc
            //email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), message.SendCustomerSubscriptionOrderConfirmation(CustomerName, SubscriptionNumber, InvoiceId, SubscriptionId), Subject, true, test, ConfigurationManager.AppSettings["EmailAddress"].ToString(), attach, FileName);
        }

        /// <summary>
        /// Function that sends email to customer with userlogin details
        /// </summary>
        /// <param name="CustomerEmail">Customer email</param>
        /// <param name="CustomerName">Name of customer</param>
        /// <param name="UserName">Username</param>
        /// <param name="Password">Password</param>
        private void SendEmailUserInfo(string CustomerEmail, string CustomerName, string UserName, string Password)
        {
            string Subject = "Brugerlogin til mobilhjulskift.dk";
            bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));

            EmailNotification.EmailNotification message = new EmailNotification.EmailNotification();
            
            Shared email = new Shared();

            // Send email to customer with us on bcc
            email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), message.SendEmailUserInfoStandard(CustomerName, UserName, Password), Subject, true, test, ConfigurationManager.AppSettings["EmailAddress"].ToString(), null, null);
        }
        
        /// <summary>
        /// Radiobutton liste function that runs when subscription is selected
        /// </summary>
        protected void rblSubscription_SelectedIndexChanged(object sender, EventArgs e)
        {
            SubscriptionSelected(Convert.ToInt32(rblSubscription.Value));
        }

        /// <summary>
        /// Function that updates UI based on selected subscription 
        /// </summary>
        /// <param name="SubscriptionId">Id on selected subscription</param>
        private void SubscriptionSelected(int SubscriptionId)
        {
            try
            {
                // Show round panel with subscription details
                rpSubscriptionInformation.Visible = true;

                // Initiate database connection
                TireServiceDB db = new TireServiceDB();

                Subscription subscription = db.GetSubscription(SubscriptionId);

                // Get subscription description
                rpSubscriptionInformation.HeaderText = subscription.Description;
                lblSubscriptionPrice.Text = string.Format("{0:N}", subscription.StandardPrice) + " kr incl. moms";

                string subscriptiondetails = subscription.DescriptionHTML;

                // Show/hide second car details
                cbSecondCarLockingBolt.Visible = rblSubscription.SelectedItem.Value.ToString() == "2";
                ddlSecondCarBrand.Visible = rblSubscription.SelectedItem.Value.ToString() == "2";
                ddlSecondCarFuelType.Visible = rblSubscription.SelectedItem.Value.ToString() == "2";
                txtSecondCarColor.Visible = rblSubscription.SelectedItem.Value.ToString() == "2";
                txtSecondCarEngineSize.Visible = rblSubscription.SelectedItem.Value.ToString() == "2";
                txtSecondCarModel.Visible = rblSubscription.SelectedItem.Value.ToString() == "2";
                txtSecondCarRegistrationNumber.Visible = rblSubscription.SelectedItem.Value.ToString() == "2";
                txtSecondCarYear.Visible = rblSubscription.SelectedItem.Value.ToString() == "2";

                lSubscriptionDetails.Text = subscriptiondetails;

                // Set link to sales terms
                lnkPaymentTerms.HRef = "~/HtmlTemplates/Betingelser.pdf";
                if (rblSubscription.SelectedItem.Value.ToString() == "4")
                {
                    lnkPaymentTerms.HRef = "~/HtmlTemplates/BetingelserEnkeltHjulskift.pdf";
                }

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception)
            {

                // Nothing
            }
        }

        /// <summary>
        /// Button function that sends email to us with request from user to be contacted on phone
        /// </summary>
        protected void btnCallMe_Click(object sender, EventArgs e)
        {
            try
            {
                string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                string message = String.Format("Kunde har brug for hjælp til bestilling<br><br>Navn: {0}<br>Telefon: {1}", txtCallMeName.Text, txtCallMePhone.Text);

                Shared email = new Shared();
                email.SendEmail(emailaddress, emailaddress, message, "Brug for hjælp til bestilling", true, test, null, null, null);

                // Change panel view in modal popup 
                pEmailSend.Visible = true;
                pNeedHelp.Visible = false;
            }
            catch (Exception)
            {
                // Nothing
            }
        }

        /// <summary>
        /// Button function that moves user back to previous step in signup form
        /// </summary>
        protected void btnPreviousStep_Click(object sender, EventArgs e)
        {
            this.StepNumber = this.StepNumber - 1;
            ChangeFormUI(this.StepNumber, this.PaymentDone);
        }

        /// <summary>
        /// Button function that moves user to next step in signup form
        /// </summary>
        protected void btnNextStep_Click(object sender, EventArgs e)
        {
            this.StepNumber = this.StepNumber + 1;
            ChangeFormUI(this.StepNumber, this.PaymentDone);

            if (this.StepNumber == 4)
            {
                // Show data entered by 
                lSubscriptionData.Text = rblSubscription.SelectedItem.Text + "<br>";
                lCustomerData.Text = "Navn: " + txtName.Text + "<br>Primær adresse: " + txtAddress.Text + ", " + txtZipCode.Text + " " + txtCity.Text + "<br>Sekundær adresse: " + txtSecondaryAddress.Text + ", " + txtSecondaryZipCode.Text + " " + txtSecondaryCity.Text + "<br>Telefon1: " + txtPhone1.Text + "<br>Telefon2: " + txtPhone2.Text + "<br>Email: " + txtEmail.Text + "<br>";
                lCarData.Text = "Reg.nr.: " + txtRegistrationNumber.Text + "<br>Mærke: " + ddlCarBrand.SelectedItem.Text.ToString() + "<br>Model: " + txtModel.Text + "<br>Motor: " + txtEngineSize.Text + "<br>Brændstof: " + ddlFuelType.SelectedItem.Text.ToString() + "<br>Farve: " + txtColor.Text + "<br>Årgang: " + txtYear.Text + "<br>Låsebolte: " + cbLockingBolt.Checked.ToString().Replace("False", "Nej").Replace("True", "Ja") + "<br>";
            }
        }

        protected void btnApproveSignUp_Click(object sender, EventArgs e)
        {
            this.StepNumber = this.StepNumber + 1;
            ChangeFormUI(this.StepNumber, this.PaymentDone);

            // Check if signup wizard completed (data saved in database) - otherwise, save data
            if (this.OrderingCompleted != true & this.StepNumber == 5)
            {
                try
                {
                    TireServiceDB db = new TireServiceDB();

                    // Create customer
                    Customer customer = new Customer();

                    int customerid = 0;
                    bool parentcompany = false;
                    int? parentcustomerid = null;
                    bool parentpayinvoice = false;
                    string companyname = null;
                    string companynumber = null;
                    int? phone2type = null;

                    if (ddlPhone2Type.SelectedItem != null)
                    {
                        phone2type = Convert.ToInt32(ddlPhone2Type.SelectedItem.Value);
                    }

                    CustomerBLL customerBLL = new CustomerBLL();
                    customerBLL.UpdateCustomer(
                                                db,
                                                customer,
                                                customerid,
                                                parentcompany,
                                                parentcustomerid,
                                                parentpayinvoice,
                                                false,
                                                companyname,
                                                companynumber,
                                                txtName.Text,
                                                txtAddress.Text,
                                                txtZipCode.Text,
                                                txtCity.Text,
                                                Convert.ToInt32(ddlCountry.Value),
                                                txtSecondaryAddress.Text,
                                                txtSecondaryZipCode.Text,
                                                txtSecondaryCity.Text,
                                                txtPhone1.Text,
                                                Convert.ToInt32(ddlPhone1Type.Value),
                                                txtPhone2.Text,
                                                phone2type,
                                                txtEmail.Text,
                                                Convert.ToBoolean(rbPrimaryAddressTimeInterval.Value), 
                                                true,
                                                true
                                            );

                    Subscription selectedsubscription = db.GetSubscription(Convert.ToInt32(rblSubscription.Value));
                    CustomerSubscription customersubscription = new CustomerSubscription();

                    // Define system userid
                    Guid userid = new Guid(ConfigurationManager.AppSettings["SystemUserId"].ToString()); // System ID - Jannik79

                    // Create customer subscription
                    CustomerSubscriptionBLL customersubscriptionBLL = new CustomerSubscriptionBLL();
                    //customersubscriptionBLL.UpdateCustomerSubscription(
                    //                            db,
                    //                            customersubscription,
                    //                            customer,
                    //                            0,
                    //                            Convert.ToInt32(rblSubscription.SelectedItem.Value),
                    //                            DateTime.Now,
                    //                            DateTime.Now.AddMonths(selectedsubscription.SubscriptionLengthMonth),
                    //                            false,
                    //                            false,
                    //                            selectedsubscription.BalancingIncluded,
                    //                            false,
                    //                            selectedsubscription.StandardPrice,
                    //                            userid,
                    //                            true,
                    //                            "Online bestilling"
                    //                        );

                    // Create car
                    Car car = new Car();

                    CarBLL carBLL = new CarBLL();
                    carBLL.UpdateCar(
                                        db,
                                        car,
                                        customersubscription,
                                        customer,
                                        0,
                                        txtRegistrationNumber.Text,
                                        Convert.ToInt32(ddlCarBrand.SelectedItem.Value),
                                        txtModel.Text ?? "-",
                                        txtEngineSize.Text ?? "-",
                                        Convert.ToInt32(ddlFuelType.Value),
                                        0 + Convert.ToInt32(txtYear.Text),
                                        txtColor.Text,
                                        (int)Shared.CarStatus.Active,
                                        null,
                                        null,
                                        true
                                    );

                    // Add tiresets for new car
                    TireSet tireset1 = new TireSet();
                    TireSet tireset2 = new TireSet();
                    TireSetBLL tiresetBLL = new TireSetBLL();
                    ContainerCargoRoomBLL containerBLL = new ContainerCargoRoomBLL();

                    // Determine what tires are on the car
                    int tireset1status, tireset2status;
                    int? tireset1container, tireset2container;
                    if (rblCurrentTireSet.SelectedItem.Value.ToString() == "0")
                    {
                        // Winter tires on car
                        tireset1status = (int)Shared.TireSetStatus.OnStock;
                        tireset1container = containerBLL.ReturnNearestContainerCargoRoomId(db, float.Parse(customer.LatitudePrimary.ToString()), float.Parse(customer.LongitudePrimary.ToString()));
                        tireset2status = (int)Shared.TireSetStatus.MountedOnCar;
                        tireset2container = null;
                    }
                    else
	                {
                        // Summer tires on car
                        tireset1status = (int)Shared.TireSetStatus.MountedOnCar;
                        tireset1container = null;
                        tireset2status = (int)Shared.TireSetStatus.OnStock;
                        tireset2container = containerBLL.ReturnNearestContainerCargoRoomId(db, float.Parse(customer.LatitudePrimary.ToString()), float.Parse(customer.LongitudePrimary.ToString()));
	                }

                    tiresetBLL.UpdateTireSet(
                                        db,
                                        tireset1,
                                        car,
                                        (int)Shared.TireType.SummerTires,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        cbLockingBolt.Checked,
                                        false,
                                        false,
                                        false,
                                        false,
                                        null,
                                        null,
                                        tireset1status,
                                        null,
                                        tireset1container,
                                        true,
                                        false,
                                        null,
                                        userid,
                                        null,
                                        true
                                    );

                    tiresetBLL.UpdateTireSet(
                                        db,
                                        tireset2,
                                        car,
                                        (int)Shared.TireType.WinterTires,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        cbLockingBolt.Checked,
                                        false,
                                        false,
                                        false,
                                        false,
                                        null,
                                        null,
                                        tireset2status,
                                        null,
                                        tireset2container,
                                        true,
                                        false,
                                        null,
                                        userid,
                                        null,
                                        true
                                    );

                    // Check if second car should be added
                    if (rblSubscription.SelectedItem.Value.ToString() == "2")
                    {
                        // Create second car
                        Car car2 = new Car();

                        carBLL.UpdateCar(
                                            db,
                                            car2,
                                            customersubscription,
                                            customer,
                                            0,
                                            txtSecondCarRegistrationNumber.Text,
                                            Convert.ToInt32(ddlSecondCarBrand.SelectedItem.Value),
                                            txtSecondCarModel.Text ?? "-",
                                            txtSecondCarEngineSize.Text ?? "-",
                                            Convert.ToInt32(ddlSecondCarFuelType.Value),
                                            0 + Convert.ToInt32(txtSecondCarYear.Text),
                                            txtSecondCarColor.Text,
                                            (int)Shared.CarStatus.Active,
                                            null,
                                            null,
                                            true
                                        );

                        // Add tiresets for new car
                        TireSet tireset3 = new TireSet();
                        TireSet tireset4 = new TireSet();

                        // Determine what tires are on the car
                        int tireset3status, tireset4status;
                        int? tireset3container, tireset4container;
                        if (rblCurrentTireSet.SelectedItem.Value.ToString() == "0")
                        {
                            // Winter tires on car
                            tireset3status = (int)Shared.TireSetStatus.OnStock;
                            tireset3container = containerBLL.ReturnNearestContainerCargoRoomId(db, float.Parse(customer.LatitudePrimary.ToString()), float.Parse(customer.LongitudePrimary.ToString()));
                            tireset4status = (int)Shared.TireSetStatus.MountedOnCar;
                            tireset4container = null;
                        }
                        else
                        {
                            // Summer tires on car
                            tireset3status = (int)Shared.TireSetStatus.MountedOnCar;
                            tireset3container = null;
                            tireset4status = (int)Shared.TireSetStatus.OnStock;
                            tireset4container = containerBLL.ReturnNearestContainerCargoRoomId(db, float.Parse(customer.LatitudePrimary.ToString()), float.Parse(customer.LongitudePrimary.ToString()));
                        }

                        tiresetBLL.UpdateTireSet(
                                            db,
                                            tireset3,
                                            car2,
                                            (int)Shared.TireType.SummerTires,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            cbLockingBolt.Checked,
                                            false,
                                            false,
                                            false,
                                            false,
                                            null,
                                            null,
                                            tireset3status,
                                            null,
                                            tireset3container,
                                            true,
                                            false,
                                            null,
                                            userid,
                                            null,
                                            true
                                        );

                        tiresetBLL.UpdateTireSet(
                                            db,
                                            tireset4,
                                            car2,
                                            (int)Shared.TireType.WinterTires,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            cbLockingBolt.Checked,
                                            false,
                                            false,
                                            false,
                                            false,
                                            null,
                                            null,
                                            tireset4status,
                                            null,
                                            tireset4container,
                                            true,
                                            false,
                                            null,
                                            userid,
                                            null,
                                            true
                                        );
                    }
                    
                    //// Create invoice
                    //InvoiceBLL invoiceBLL = new InvoiceBLL();
                    //Invoice invoice = new Invoice();

                    //invoiceBLL.UpdateInvoice(
                    //                            db,
                    //                            invoice,
                    //                            customer,
                    //                            0,
                    //                            DateTime.Now,
                    //                            DateTime.Now.AddDays(2),
                    //                            (int)Shared.InvoiceStatus.Invoiced,
                    //                            (int)Shared.Currency.DKK,
                    //                            true
                    //                        );

                    //InvoiceDetailBLL invoicedetailBLL = new InvoiceDetailBLL();
                    //InvoiceDetail invoicedetail = new InvoiceDetail();

                    //invoicedetailBLL.UpdateInvoiceDetailWithCustomerSubscription(
                    //                            db,
                    //                            invoice, invoicedetail,
                    //                            customersubscription,
                    //                            0,
                    //                            db.GetSubscriptionDescription(customersubscription.SubscriptionId),
                    //                            customersubscription.Price,
                    //                            true
                    //                        );

                    // Commit changes to database
                    db.SubmitChanges();

                    // Handle E-conomic interface
                    EconomicInterface ecoInterface = new EconomicInterface();
                    
                    // Create debtor
                    ecoInterface.CreateDebtor(customer, db);
                    
                    // Create subscriber
                    ecoInterface.CreateSubscriber(Convert.ToInt32(selectedsubscription.SubscriptionId), customersubscription, null, customer.Name);


                    // Create invoice
                    string invoiceid = ecoInterface.CreateSubscriptionInvoice(db, customer.CustomerId, customersubscription, customersubscription.Price);

                    try
                    {
                        // Create user
                        MembershipUser user = Membership.CreateUser(customer.Email, customer.Phone1.ToString(), customer.Email);

                        // Add user to customer role
                        Roles.AddUserToRole(user.UserName, "Kunde");

                        customer.UserId = new Guid(user.ProviderUserKey.ToString());

                        db.SubmitChanges();

                        // Send email to user with user information
                        SendEmailUserInfo(customer.Email, customer.Name, user.UserName, customer.Phone1.ToString());
                    }
                    catch (Exception ex)
                    {
                        // Nothing, but error does not stop signup process for customer

                        // Send email to mobil hjulskift with error
                        string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                        bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                        string message = String.Format("Systemet fejlede ved forsøg på at oprette kunde login<br><br>Email: {0}<br><br>Fejl: {1}", customer.Email, ex.Message);

                        Shared email = new Shared();
                        email.SendEmail(emailaddress, emailaddress, message, "Fejl ved oprettelse af brugerlogin", true, test, null, null, null);
                    }

                    // Set page propertie that indicates that ordering is completed
                    this.OrderingCompleted = true;

                    // Change UI
                    // Show subscriptionnumber (CustomerId-SubscriptionId-CustomerSubscriptionId)
                    string subscriptionnumber = customer.CustomerId.ToString() + "-" + customersubscription.SubscriptionId.ToString() + "-" + customersubscription.CustomerSubscriptionId.ToString();
                    lblSubscriptionNumber.Text = subscriptionnumber;
                    // Set customerid, orderid and amount for Payment
                    hfCustomerId.Value = customer.CustomerId.ToString();
                    hfAmount.Value = customersubscription.Price.ToString();
                    hfInvoiceId.Value = invoiceid;
                    //hfInvoiceId.Value = invoice.InvoiceId.ToString();
                    //hfInvoiceGuid.Value = invoice.InvoiceGuid.ToString();
                    lnkInvoice.NavigateUrl = string.Format("~/Reports/View/Faktura.aspx?CustomerId={0}&InvoiceId={1}", customer.CustomerId.ToString(), invoiceid);
                    lnkInvoice.Text = "Faktura " + invoiceid;
                    lnkInvoice2.NavigateUrl = string.Format("~/Reports/View/Faktura.aspx?CustomerId={0}&InvoiceId={1}", customer.CustomerId.ToString(), invoiceid);
                    lnkInvoice2.Text = "Faktura " + invoiceid;


                    // Send email to customer with information on order
                    
                    // Generate invoice attachment


                    SendEmail(customer.Email, customer.Name, subscriptionnumber, invoiceid, customersubscription.SubscriptionId, ecoInterface.GetInvoice(Convert.ToInt32(invoiceid)), "Faktura" + invoiceid + ".pdf");

                    // Dispose database connection
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    // Send email to mobil hjulskift with error and contact information on customer
                    string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                    bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                    string message = String.Format("Systemet fejlede ved forsøg på at oprette kunde<br><br>Navn: {0}<br>Telefon: {1}<br>Systemfejl: {2}", txtName.Text, txtPhone1.Text, ex.Message);

                    Shared email = new Shared();
                    email.SendEmail(emailaddress, emailaddress, message, "Fejl ved bestilling", true, test, null, null, null);

                    // Show message to user
                    pErrorMessage.Visible = true;

                    // Hide other form steps
                    step1SubscriptionChoice.Visible = false;
                    step2CustomerInformation.Visible = false;
                    step3CarInformation.Visible = false;
                    step4Approval.Visible = false;
                    step5Payment.Visible = false;
                }
            }
        }

        protected void rblPaymentMethod_SelectedIndexChanged(object sender, EventArgs e)
        {
            // UDKOMMENTERET 06-09-2011: JANNIK

            //// Show round panel with payment method
            //rpPaymentMethod.Visible = true;

            //// Bank transfer
            //if (rblPaymentMethod.Value == "0")
            //{
            //    pManualPayment.Visible = true;
            //    pOnlinePayment.Visible = false;
            //    pPaypal.Visible = false;
            //}

            // TODO: Først muligt når vi har betalingsgateway på
            //if (rblPaymentMethod.Value == "1")
            //{
            //    pOnlinePayment.Visible = true;
            //    pManualPayment.Visible = false;
            //    pPaypal.Visible = false;  
            //}
            
            // Paypal payment
            //if (rblPaymentMethod.Value == "2")
            //{
            //    pManualPayment.Visible = false;
            //    pOnlinePayment.Visible = false;
            //    pPaypal.Visible = true;
            //}
        }

        protected void btnPaypalPayment_Click(object sender, EventArgs e)
        {
            try
            {
                // *** Set a flag so we know we redirected to minimize spoofing
                Session["PayPal_Redirected"] = "True";

                string customerid = hfCustomerId.Value.ToString();
                string amount = string.Format("{0:N}", hfAmount.Value.Replace(",", "."));
                string invoiceguid = hfInvoiceGuid.Value.ToString();
                string invoiceid = hfInvoiceId.Value.ToString();
                //string NotifyURL = Convert.ToString(ConfigurationManager.AppSettings["PayPalNotifyURL"]) + "?Id=" + invoiceguid + "Action=1";


                NameValueCollection data = HelperFunctions.PaypalOnlinePayment(customerid,
                                              Convert.ToString(ConfigurationManager.AppSettings["PayPalReturnURL"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["PayPalCancelURL"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["PayPalBusinessEmail"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["LogoURL"]),
                                              txtEmail.Text,
                                              Convert.ToString(ConfigurationManager.AppSettings["PayPalCurrencyCode"]),
                                              "Mobilhjulskift abonnement",
                                              amount,
                                              invoiceguid,
                                              invoiceid
                                             );

                HttpHelper.RedirectAndPOST(this.Page, Convert.ToString(ConfigurationManager.AppSettings["PayPalAuthURL"]), data, "_xclick");
            }
            catch (Exception ex)
            {
                // TODO: Write code
                
            }
        }

        /// <summary>
        /// Button function for online payment that execute payment with credit card
        /// </summary>
        protected void btnPayment_Click(object sender, EventArgs e)
        {
            try
            {
                string amount = string.Format("{0:N}", hfAmount.Value).Replace(".", "").Replace(",", "");
                string invoiceguid = hfInvoiceGuid.Value.ToString();
                string invoiceid = hfInvoiceId.Value.ToString();
                string acceptURL = "www.mobilhjulskift.dk/Betal.aspx?Id=" + invoiceguid + "Action=1";
                string declineURL = "www.mobilhjulskift.dk/BetalFejl.aspx?Id=" + invoiceguid;

                NameValueCollection data = HelperFunctions.OnlinePayment(amount, 
                                              invoiceid,
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopCurrency"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopMd5Key"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopId"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopOrderPrefix"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopPayType"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopCardType"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopLanguage"]),
                                              acceptURL,
                                              declineURL
                                             );

                HttpHelper.RedirectAndPOST(this.Page, Convert.ToString(ConfigurationManager.AppSettings["ShopAuthURL"]), data);
            }
            catch (Exception ex)
            {
                // TODO: Write code
                
            }
        }

        protected void lbtnCancelSignup_Click(object sender, EventArgs e)
        {
            try
            {
                // Send email to mobil hjulskift with info about customer has left ordering form
                string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                string message = String.Format("Kunde gik til startsiden ved forsøg på at oprette kunde<br><br>Navn: {0}<br>Adresse: {1}<br>Postnr og by: {2} {3}<br>Telefon: {4}<br>Telefon2: {5}", txtName.Text, txtAddress.Text, txtZipCode.Text, txtCity.Text, txtPhone1.Text, txtPhone2.Text);

                Shared email = new Shared();
                email.SendEmail(emailaddress, emailaddress, message, "Annullering af bestillingsproces", true, test, null, null, null);

                // Redirect user to startpage
                Response.Redirect("~/Index.aspx");
            }
            catch (Exception ex)
            {
                // Nothing - redirect user

                // Redirect user to startpage
                Response.Redirect("~/Index.aspx");
            }
        }

        protected void cbApproveTermns_CheckedChanged(object sender, EventArgs e)
        {
            //btnApproveSignUp.ClientEnabled = cbApproveTermns.Checked;
            btnApproveSignUp.Enabled = cbApproveTermns.Checked;
        }

        protected void cbUsePrimaryAddress_CheckedChanged(object sender, EventArgs e)
        {
            if (cbUsePrimaryAddress.Checked)
            {
                // Set secondary fields to primary adsress
                txtSecondaryAddress.Text = txtAddress.Text;
                txtSecondaryZipCode.Text = txtZipCode.Text;
                txtSecondaryCity.Text = txtCity.Text;
            }
            else
            {
                // Clear secondary fields
                txtSecondaryAddress.Text = "";
                txtSecondaryZipCode.Text = "";
                txtSecondaryCity.Text = "";
            }
        }

    }
}